#include "commoditysale.h"
#include "ui_commoditysale.h"
#include "lockscreen.h"
#include "inquiresql.h"
#include "inquirepurchasecommodity.h"
#include <QCheckBox>
#include "mainwindow.h"
#include <QKeyEvent>
#include "modifypricediscount.h"
#include "checkout.h"
#include "inquirememberprofile.h"
#include <QDateTime>
#include <QMessageBox>
#include "printmemberpassword.h"
#include <QDebug>

#include <QDesktopWidget>

CommoditySale::CommoditySale(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CommoditySale)
{
    ui->setupUi(this);
    this->setLayout(ui->MainLayout);
    m_lastClick = -1;

    //设置自定义的鼠标指针图案
    QCursor *myCursor= new QCursor(QPixmap(":/Mouse/Image/mouse/mouse.png"),15,10);
    setCursor(*myCursor);

    m_isAddSubQuantity = false;
    m_updateSaleCommodityInformation = false;
    m_printMemberPassword = new PrintMemberPassword;
    ui->labelSupermarketName->setAlignment(Qt::AlignCenter); 

//    ui->lineEditInquireCommodity->setFocus();
//    ui->lineEditInquireCommodity->selectAll();

    ui->lineEditInquireCommodity->installEventFilter(this);
    ui->lineEditMembershipNumber->installEventFilter(this);
    ui->tableWidgetSale->installEventFilter(this);
    QWidget::installEventFilter(this);

    QHeaderView* vheaderView = ui->tableWidgetSale->verticalHeader();
    vheaderView->setHidden(true);

    m_lockScreen = new LockScreen(this);
    m_modifyPriceDiscount = new ModifyPriceDiscount(this);
    m_inquirePurchaseCommodity = new InquirePurchaseCommodity(this);
    m_checkout = new Checkout(this);
    m_inquireMemberProfile = new InquireMemberProfile(this);

    m_lockScreen->hide();
    m_modifyPriceDiscount->hide();
    m_inquirePurchaseCommodity->hide();
    m_inquireMemberProfile->hide();
    m_checkout->hide();

    setQtableWidgetHeader();

    ui->tableWidgetSale->setColumnWidth(0,30);
    ui->tableWidgetSale->setColumnWidth(1,80);
    ui->tableWidgetSale->setColumnWidth(2,240);
    ui->tableWidgetSale->setColumnWidth(3,75);
    ui->tableWidgetSale->setColumnWidth(4,75);
    ui->tableWidgetSale->setColumnWidth(5,75);
    ui->tableWidgetSale->setColumnWidth(6,110);
    ui->tableWidgetSale->setColumnWidth(7,120);
//    ui->tableWidgetSale->setColumnWidth(8,120);
    ui->tableWidgetSale->setColumnWidth(8,50);

    //设置列宽可拖动
//    ui->tableWidgetSale->horizontalHeader()->setResizeMode(QHeaderView::Interactive);
//    ui->tableWidgetSale->verticalHeader()->setResizeMode(QHeaderView::Interactive);

    //设置销售单号
    setSalesOrderFormNumber();

    eliminationPushButtonBorder();

    slotUpdateSystemSettingsInformation();

    connect(m_inquirePurchaseCommodity, SIGNAL(displayCommodityInformation(QString)),
            this, SLOT(slotDisplayCommodityInformation(QString)));
    connect(m_inquireMemberProfile, SIGNAL(displayMemberInformation(QString)),
            this, SLOT(slotJudgementMemberPassword(QString)));
    connect(m_modifyPriceDiscount, SIGNAL(updateSalePriceDiscount(SaleDetail)),
            this, SLOT(slotUpdateSalesPriceDiscount(SaleDetail)));
    connect(m_printMemberPassword, SIGNAL(clearMemberInformation()),
            this, SLOT(on_pushButtonClearMember_clicked()));
    connect(m_printMemberPassword, SIGNAL(displayMemberInformation(QString)),
            this, SLOT(slotDisplayMemberInformation(QString)));
    connect(m_checkout, SIGNAL(signalInit()),
            this, SLOT(slotInit()));
}

CommoditySale::~CommoditySale()
{
    delete ui;
}

bool CommoditySale::eventFilter(QObject *target, QEvent *event)
{
    if ( target == ui->lineEditInquireCommodity || target == ui->lineEditMembershipNumber
      || target == ui->tableWidgetSale || target == this)
    {
        if (event->type() == QEvent::FocusOut)
        {
            if (target == ui->tableWidgetSale)
            {
                ui->tableWidgetSale->setStyleSheet("background-color:white");
                return true;
            }
        }
        if (event->type() == QEvent::FocusIn)
        {
            if (target == ui->tableWidgetSale)
            {
//                ui->tableWidgetSale->setStyleSheet("background-color:#FFEBCD");
                ui->tableWidgetSale->setStyleSheet("\
                background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 1, \
                    stop: 0 rgba(255, 0, 0, 30%), stop: 0.2 rgba(255, 128, 0, 30%), \
                    stop: 0.4 rgba(255, 255, 0, 30%), stop: 0.6 rgba(0, 255, 0, 30%), \
                    stop: 0.8 rgba(0, 128, 255, 30%), stop: 1 rgba(128, 0, 255, 30%)); ");
                return true;
            }
        }
        if (event->type() == QEvent::KeyRelease)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
            if (keyEvent->key() == Qt::Key_F11)
            {
                on_pushButtonCheckout_clicked();
                return true;
            }
            if (keyEvent->key() == Qt::Key_F9 || keyEvent->key() == Qt::Key_D)
            {
                on_pushButtonDelete_clicked();
                return true;
            }
            if (keyEvent->key() == Qt::Key_Home)
            {
                emit returnHomePage();
                return true;
            }
        }
        if (event->type() == QEvent::FocusOut)
        {
            if (target == ui->lineEditInquireCommodity)
            {
                if (m_lastClick != lineEditMembershipNumber)
                    m_lastClick = -1;
            }
            if (target == ui->lineEditMembershipNumber)
            {
                if (m_lastClick != lineEditInquireCommodity)
                    m_lastClick = -1;
            }
        }
        //鼠标左键按下事件
        if (event->type() == QEvent::MouseButtonPress)
        {
            QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
            if (mouseEvent->button() == Qt::LeftButton)
            {
                if (target == ui->lineEditInquireCommodity)
                {
                    if (m_lastClick != lineEditInquireCommodity){
                        m_lastClick = lineEditInquireCommodity;
                        ui->lineEditInquireCommodity->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditInquireCommodity)
                    {
                        goto flag;
                    }
                }
                if (target == ui->lineEditMembershipNumber)
                {
                    if (m_lastClick != lineEditMembershipNumber){
                        m_lastClick = lineEditMembershipNumber;
                        ui->lineEditMembershipNumber->selectAll();
                        return true;
                    }else if (m_lastClick == lineEditMembershipNumber)
                    {
                        goto flag;
                    }
                }
            }
        }
        //键盘事件
        if (event->type() == QEvent::KeyPress)
        {
            QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
            if (keyEvent->key() == Qt::Key_Escape || keyEvent->key() == Qt::Key_C)
            {
                on_pushButtonClear_clicked();
                return true;
            }
            if ((keyEvent->key() == Qt::Key_Enter) || (keyEvent->key() == Qt::Key_Return))
            {
                if (target == ui->lineEditInquireCommodity)
                {
                    if (!ui->lineEditInquireCommodity->text().isEmpty())
                    {
                        HandleLineEditCommodityInformation();
                        return true;
                    }
                }
                if (target == ui->lineEditMembershipNumber)
                {
                    if (!ui->lineEditMembershipNumber->text().isEmpty())
                    {
                        handleLineEditMembershipNumber();
                        return true;
                    }
                }
            }
            if (keyEvent->key() == Qt::Key_F1)
            {
                if (target == ui->lineEditMembershipNumber)
                {
                    ui->lineEditInquireCommodity->setFocus();
                    ui->lineEditInquireCommodity->selectAll();
                    return true;
                }
                if (target == ui->lineEditInquireCommodity)
                {
                    if (ui->tableWidgetSale->rowCount())
                        ui->tableWidgetSale->setFocus();
                    else
                    {
                        ui->lineEditMembershipNumber->setFocus();
                        ui->lineEditMembershipNumber->selectAll();
                    }
                    return true;
                }
                if (target == ui->tableWidgetSale)
                {
                    ui->lineEditMembershipNumber->setFocus();
                    ui->lineEditMembershipNumber->selectAll();
                    return true;
                }
                else
                {
                    ui->lineEditInquireCommodity->setFocus();
                    ui->lineEditInquireCommodity->selectAll();
                    return true;
                }
            }
            if (keyEvent->key() == Qt::Key_PageUp || keyEvent->key() == Qt::Key_A)
            {
                if (target == ui->lineEditMembershipNumber
                        || target == ui->lineEditInquireCommodity)
                    goto flag;
                SaleDetail saleDetail = m_currentTableWidgetList.at(
                            ui->tableWidgetSale->currentRow());
                if (saleDetail.get_saleQuantity().toInt()
                        < saleDetail.get_stockQuantity().toInt())
                    saleDetail.set_saleQuantity(QString::number(
                        m_currentTableWidgetList.at(
                            ui->tableWidgetSale->currentRow()).get_saleQuantity().toInt() + 1));
                else
                {
                    QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."),
                                         tr("\n此产品库存不足,无法增加销售数量!") );
                }
                m_currentTableWidgetList.replace(
                            ui->tableWidgetSale->currentRow(), saleDetail);
                m_isAddSubQuantity = true;
                int currentRow = ui->tableWidgetSale->currentRow();
                displaySalesCommodityInformation();
                ui->tableWidgetSale->setCurrentItem(
                        ui->tableWidgetSale->item(currentRow, 0));
//                event->accept();
                return true;
            }
            if (keyEvent->key() == Qt::Key_PageDown || keyEvent->key() == Qt::Key_S)
            {
                if (target == ui->lineEditMembershipNumber
                        || target == ui->lineEditInquireCommodity)
                    goto flag;
                SaleDetail saleDetail = m_currentTableWidgetList.at(
                            ui->tableWidgetSale->currentRow());
                if (m_currentTableWidgetList.at(
                            ui->tableWidgetSale->currentRow()).get_saleQuantity().toInt() > 0)
                {
                    saleDetail.set_saleQuantity(QString::number(
                        m_currentTableWidgetList.at(
                            ui->tableWidgetSale->currentRow()).get_saleQuantity().toInt() - 1));
                    m_currentTableWidgetList.replace(
                                ui->tableWidgetSale->currentRow(), saleDetail);
                    m_isAddSubQuantity = true;
                    int currentRow = ui->tableWidgetSale->currentRow();
                    displaySalesCommodityInformation();
                    ui->tableWidgetSale->setCurrentItem(
                            ui->tableWidgetSale->item(currentRow, 0));
                }
//                event->accept();
                return true;
            }
        }
    }
flag:
    return QWidget::eventFilter(target, event);
}

void CommoditySale::setFocus()
{
    ui->lineEditInquireCommodity->setFocus();
}

void CommoditySale::slotUpdateSystemSettingsInformation()
{
    m_systemSet = m_sql->InquireSystemSettingsInformation();
    ui->labelSupermarketName->setText(m_systemSet.get_title());
}

void CommoditySale::setQtableWidgetHeader()
{
    QStringList headers;
    headers << tr("NO") << tr("商品内码") << tr("商品名称")
            << tr("原价") << tr("折扣") << tr("数量")
            << tr("售价") << tr("销售小计") << tr("积分");

    ui->tableWidgetSale->setColumnCount(9);
    ui->tableWidgetSale->setHorizontalHeaderLabels(headers);

    for (int i = 0; i < 9; ++i)
    {
        if (i >= 5 && i<= 7)
        {
            ui->tableWidgetSale->horizontalHeaderItem(i)->setFont(QFont("Helvetica", 12, 2, false));
            ui->tableWidgetSale->horizontalHeaderItem(i)->setTextColor(QColor(0,0,255));
            continue;
        }
        ui->tableWidgetSale->horizontalHeaderItem(i)->setFont(QFont("Helvetica", 12, 2, false));
        ui->tableWidgetSale->horizontalHeaderItem(i)->setTextColor(QColor(200,111,30));
    }
}

void CommoditySale::displaySalesCommodityInformation()
{

    ui->tableWidgetSale->clear();
    setQtableWidgetHeader();

    //显示销售商品信息
    ui->tableWidgetSale->setRowCount(m_currentTableWidgetList.count());

    int quantityLaber = 0;
    double originalPriceLaber = 0, realSellingPriceLaber = 0;
    for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
    {
        //散客购物
        QString originalPrice ,discount, realSellingPrice;
        if (ui->labelName->text().isEmpty())
        {
            originalPrice = m_currentTableWidgetList.at(i).get_sellingPrice();
            switch(m_systemSet.get_generalCustomerPrice())
            {
                case RetailPrice:
                    discount = "100";
                    realSellingPrice = m_currentTableWidgetList.at(i).get_sellingPrice();
                    break;
                case RetailPrice_Multiply_CommodityDiscount:
//                    discount = m_currentTableWidgetList.at(i).get_discount();
                    discount = m_sql->InquireCommodityInformationValue(
                                m_currentTableWidgetList.at(i).get_commodityBarcode())
                            .get_discount();
                    realSellingPrice = QString::number(
                    m_currentTableWidgetList.at(i).get_sellingPrice().toDouble() *
                    m_currentTableWidgetList.at(i).get_discount().toDouble() / 100, 'd', 2);
                    break;
                default:
                    qDebug() << "error";
                    break;
            }
        }
        //会员购物
        else
        {
            if (m_systemSet.get_memberPrice() >= RetailPrice
             && m_systemSet.get_memberPrice() <=
                    RetailPrice_Multiply_CommodityDiscount_Multiply_MemberDiscount)
            {
                originalPrice = m_currentTableWidgetList.at(i).get_sellingPrice();
            }
            else
            {
                originalPrice = m_currentTableWidgetList.at(i).get_memberPrice();
            }
            switch(m_systemSet.get_memberPrice())
            {
                case RetailPrice:
                case MemberPrice:
                    discount = "100";
                    realSellingPrice = originalPrice;
                    break;
                case RetailPrice_Multiply_CommodityDiscount:
                case MemberPrice_Multiply_CommodityDiscount:
//                    discount = m_currentTableWidgetList.at(i).get_discount();
                    discount = m_sql->InquireCommodityInformationValue(
                                m_currentTableWidgetList.at(i).get_commodityBarcode())
                            .get_discount();
                    realSellingPrice = QString::number(
                    originalPrice.toDouble() *
                    discount.toDouble() / 100, 'd', 2);
                    break;
                case RetailPrice_Multiply_MemberDiscount:
                case MemberPrice_Multiply_MemberDiscount:
                    discount = m_memberDiscount;
//                    discount = ui->labelDiscount->text();
                    realSellingPrice = QString::number(
                    originalPrice.toDouble() *
                    discount.toDouble() / 100, 'd', 2);
                    break;
                case RetailPrice_Multiply_CommodityDiscount_Multiply_MemberDiscount:
                case MemberPrice_Multiply_CommodityDiscount_Multiply_MemberDiscount:
//                    discount = QString::number(m_memberDiscount.toDouble() *
//                        m_currentTableWidgetList.at(i).get_discount().toDouble() / 100);
                    discount = QString::number(m_memberDiscount.toDouble() *
                        m_sql->InquireCommodityInformationValue(
                        m_currentTableWidgetList.at(i).get_commodityBarcode())
                        .get_discount().toDouble() / 100);
//                    discount = QString::number(ui->labelDiscount->text().toDouble() *
//                        m_currentTableWidgetList.at(i).get_discount().toDouble() / 100);
                    realSellingPrice = QString::number(
                    originalPrice.toDouble() *
                    discount.toDouble() / 100, 'd', 2);
                    break;
                default:
                    qDebug() << "error";
                    break;
            }
        }

        QString salesSum;
        if (m_updateSaleCommodityInformation)
        {
            m_updateSaleCommodityInformation = false;
            salesSum = m_currentTableWidgetList.at(i).get_saleSum();
            discount = m_currentTableWidgetList.at(i).get_discount();
            realSellingPrice = m_currentTableWidgetList.at(i).get_realSellingPrice();
        }
        else
        {
            salesSum = QString::number(realSellingPrice.toDouble() *
                    m_currentTableWidgetList.at(i)
                    .get_saleQuantity().toInt(), 'd', 2);
        }

        SaleDetail saleCommodity =
                m_currentTableWidgetList.at(i);
//    QString originalPrice ,discount, realSellingPrice;
        saleCommodity.set_originalPrice(originalPrice);
        saleCommodity.set_discount(discount);
        saleCommodity.set_realSellingPrice(realSellingPrice);  //?sellprice not insert
        saleCommodity.set_saleSum(salesSum);
        if (ui->labelName->text().isEmpty())
            saleCommodity.set_integration(false);
        else
            saleCommodity.set_integration(true);
        m_currentTableWidgetList.replace(
                    i, saleCommodity);  //?

        QTableWidgetItem *NO      = new QTableWidgetItem(
                    QString::number(i));
        QTableWidgetItem *commodityBarcode      = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_commodityBarcode());
        QTableWidgetItem *commodityName         = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_commodityName());
        QTableWidgetItem *quantity                  = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_saleQuantity());
//        QTableWidgetItem *original                  = new QTableWidgetItem(
//                    originalPrice);
//        QTableWidgetItem *commoditydDiscount      = new QTableWidgetItem(
//                    discount + "%");
//        QTableWidgetItem *sellingPrice         = new QTableWidgetItem(
//                    realSellingPrice);
////        QTableWidgetItem *saleSum         = new QTableWidgetItem(
////                        QString::number(realSellingPrice.toDouble() *
////                    m_currentTableWidgetList.at(i).get_saleQuantity().toInt(), 'd', 2));
//        QTableWidgetItem *saleSum         = new QTableWidgetItem(salesSum);

        QTableWidgetItem *original                  = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_originalPrice());
        QTableWidgetItem *commoditydDiscount      = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_discount() + "%");
        QTableWidgetItem *sellingPrice         = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_realSellingPrice());
//        QTableWidgetItem *saleSum         = new QTableWidgetItem(
//                        QString::number(realSellingPrice.toDouble() *
//                    m_currentTableWidgetList.at(i).get_saleQuantity().toInt(), 'd', 2));
        QTableWidgetItem *saleSum         = new QTableWidgetItem(
                    m_currentTableWidgetList.at(i).get_saleSum());

//        if (m_updateSaleCommodityInformation)
//        {
//            SaleDetail saleCommodity = m_currentTableWidgetList.at(i);
//            saleCommodity.set_saleSum(salesSum);
//            saleCommodity.set_discount(discount);
//            saleCommodity.set_realSellingPrice(realSellingPrice);
//            m_currentTableWidgetList.replace(i, saleCommodity);
//            m_updateSaleCommodityInformation = false;
//        }

        QCheckBox *integration = new QCheckBox;
//        integration->setFocusPolicy(Qt::NoFocus);
        integration->setStyleSheet("\
            QCheckBox:checked { color: green; }\
            QCheckBox::indicator { width: 18px; height: 18px; }\
            QCheckBox::indicator:checked \
            { image: url(:/CommoditySale/Image/CommoditySale/checkbox.gif);}\
            ");
        if (ui->labelName->text().isEmpty())
            integration->setEnabled(false);
        else
        {
            integration->setEnabled(true);
            integration->setCheckState(Qt::Checked);
        }

        //设置对齐方式
        NO->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        commodityBarcode->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        commodityName->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        quantity->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter );
        original->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        commoditydDiscount->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        sellingPrice->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );
        saleSum->setTextAlignment(Qt::AlignRight | Qt::AlignVCenter );

        //设置文字颜色
        quantity->setTextColor(QColor(255, 0, 255));
        sellingPrice->setTextColor(QColor(255, 0, 255));
        saleSum->setTextColor(QColor(255, 0, 255));

        NO->setFont(QFont("DejaVu Sans", 11, 2, false));
        commodityBarcode->setFont(QFont("DejaVu Sans", 11, 2, false));
        commodityName->setFont(QFont("DejaVu Sans", 11, 2, false));
        quantity->setFont(QFont("DejaVu Sans", 11, 2, false));
        original->setFont(QFont("DejaVu Sans", 11, 2, false));
        commoditydDiscount->setFont(QFont("DejaVu Sans", 11, 2, false));
        sellingPrice->setFont(QFont("DejaVu Sans", 11, 2, false));
        saleSum->setFont(QFont("DejaVu Sans", 11, 2, false));

        ui->tableWidgetSale->setItem(i, 0, NO);
        ui->tableWidgetSale->setItem(i, 1, commodityBarcode);
        ui->tableWidgetSale->setItem(i, 2, commodityName);
        ui->tableWidgetSale->setItem(i, 3, original);
        ui->tableWidgetSale->setItem(i, 4, commoditydDiscount);
        ui->tableWidgetSale->setItem(i, 5, quantity);
        ui->tableWidgetSale->setItem(i, 6, sellingPrice);
        ui->tableWidgetSale->setItem(i, 7, saleSum);
        ui->tableWidgetSale->setCellWidget(i, 8, integration);

        quantityLaber += m_currentTableWidgetList.at(i).get_saleQuantity().toInt();
        originalPriceLaber += QString::number(originalPrice.toDouble() *
            m_currentTableWidgetList.at(i).get_saleQuantity().toInt(), 'd', 2).toDouble();
        realSellingPriceLaber += QString::number(realSellingPrice.toDouble() *
            m_currentTableWidgetList.at(i).get_saleQuantity().toInt(), 'd', 2).toDouble();
    }

    if (!m_isAddSubQuantity)
        ui->tableWidgetSale->setCurrentItem(
                ui->tableWidgetSale->item(m_currentTableWidgetList.count() - 1, 0));
//    else
//        ui->tableWidgetSale->setCurrentItem()
    m_isAddSubQuantity = false;

    //显示结帐信息 总金额，原价，数量
    ui->labelTotal->setText(QString::number(realSellingPriceLaber, 'd', 2));
    ui->labelQuantity->setText(QString::number(quantityLaber, 'd', 0));
    ui->labelOriginal->setText(QString::number(originalPriceLaber, 'd', 2));
    setTableWidgetColor();

    if (m_systemSet.get_modifyWindowPopsUp())
    on_tableWidgetSale_cellDoubleClicked(ui->tableWidgetSale->currentRow(), 0);
}

//void CommoditySale::updateSalesCommodityInformation()
//{

//}

void CommoditySale::setTableWidgetColor()
{
    for (int i = 0; i < ui->tableWidgetSale->rowCount(); ++i)
    {
        if (i % 2 == 0)
        {
            for (int j = 0; j < ui->tableWidgetSale->columnCount(); ++j)
            {
                QTableWidgetItem *item = ui->tableWidgetSale->item(i,j);
                if (item)
                {
                    const QColor color = QColor(252,222,156);
                    item->setBackgroundColor(color);
                }
            }
        }
    }
}

void CommoditySale::addSalesCommodity(QString commodityBarcode)
{
    //如果购买商品重复，则直接添加数量
    for (int i = 0; i < m_currentTableWidgetList.count(); ++i)
    {
        if (m_currentTableWidgetList.at(i).get_commodityBarcode() == commodityBarcode)
        {
            SaleDetail saleDetail = m_currentTableWidgetList.at(i);
            if ( saleDetail.get_saleQuantity().toInt()
                    < saleDetail.get_stockQuantity().toInt() )
            {
//                qDebug() << saleDetail.get_saleQuantity();
//                qDebug() << saleDetail.get_stockQuantity();
                saleDetail.set_saleQuantity(QString::number(
                    m_currentTableWidgetList.at(i).get_saleQuantity().toInt() + 1));
            }
            else
            {
                QMessageBox::warning(this, tr("(☆_☆)温馨提示 ..."),
                                     tr("\n此产品库存不足,无法增加销售数量!") );
            }
            m_currentTableWidgetList.replace(i, saleDetail);
            return;
        }
    }

//    SaleDetail(const QString commodityBarcode, const QString commodityName, const QString cost,
//               const QString discount, const QString saleQuantity,  const QString sellingPrice,
//               const QString memberPrice, const QString realSellingPrice, const QString saleSum,
//               const QString saleStaffName, const bool integration, const QString stockQuantity,
//               const QString originalPrice)

    Commodity m_commodity = m_sql->InquireCommodityInformationValue(commodityBarcode);
    SaleDetail temp(m_commodity.get_commodityBarcode(),
                    m_commodity.get_commodityName(),
                    m_commodity.get_cost(),
                    m_commodity.get_discount(),
                    "1", m_commodity.get_sellingPrice(),
                    m_commodity.get_memberPrice(), "0.00", "0.00",
                    m_sql->InquireStaffName(MainWindow::staffID),
                    false, m_commodity.get_stockQuantity(), "0.00");
    m_currentTableWidgetList.append(temp);
}

void CommoditySale::HandleLineEditCommodityInformation()
{
    m_commodityList.clear();
    m_commodityList = m_sql->InquireCommodityInformation();

    for(int i = 0; i < m_commodityList.count(); ++i)
    {
        if (ui->lineEditInquireCommodity->text() == m_commodityList.at(i).get_commodityBarcode())
        {
            slotDisplayCommodityInformation(ui->lineEditInquireCommodity->text());
            ui->lineEditInquireCommodity->setFocus();
            ui->lineEditInquireCommodity->setText(NULL);
            return;
        }
    }

    m_inquirePurchaseCommodity->changelineEditInquire(
                ui->lineEditInquireCommodity->text());
    m_inquirePurchaseCommodity->setWindowFlags(
                Qt::FramelessWindowHint | Qt::Dialog);
    QPoint GlobalPoint(ui->pushButtonInquireCommodity->mapToGlobal(QPoint(0, 0)));
    int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
    int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
    m_inquirePurchaseCommodity->setGeometry(x - 250, y - 440, 800, 425);
//    //在对 QWidget 操作时，不能操作其他东西
//    m_inquirePurchaseCommodity->setWindowModality(Qt::ApplicationModal);
//    m_inquirePurchaseCommodity->setAttribute(Qt::WA_ShowModal, true);
    m_inquirePurchaseCommodity->show();
}

void CommoditySale::handleLineEditMembershipNumber()
{
    m_memberList.clear();
    m_memberList = m_sql->InquireMemberProfile();

    for(int i = 0; i < m_memberList.count(); ++i)
    {
        if (ui->lineEditMembershipNumber->text() == m_memberList.at(i).get_personID())
        {
            slotDisplayMemberInformation(ui->lineEditMembershipNumber->text());
            ui->lineEditInquireCommodity->setFocus();
            ui->lineEditInquireCommodity->setText(NULL);
            return;
        }
    }
    on_pushButtonInquireMember_clicked();
}

void CommoditySale::setSalesOrderFormNumber()
{
    m_salesOrderFormList = m_sql->InquireSalesOrderForm("all", "all", -1, NULL);
    QDateTime time = QDateTime::currentDateTime();//获取系统现在的时间
    if (m_salesOrderFormList.at(m_salesOrderFormList.count() - 1).get_salesDate()
            < time.toString("yyyy-MM-dd"))
    {
        QString str = time.toString("yyyyMMdd"); //设置显示格式
        ui->labelSalesOrderFormNumber->setText("XS"+str+"0001");
    }
    else
    {
        QString str = time.toString("yyyyMMdd"); //设置显示格式
        ui->labelSalesOrderFormNumber->setText("JH"+str+QString::number(m_salesOrderFormList
                                    .at(m_salesOrderFormList.count() - 1)
                                    .get_saleOrderFormNumber()
                                    .mid(10, 4).toInt() + 1).rightJustified(4, '0'));
    }
}

void CommoditySale::eliminationPushButtonBorder()
{
    //消除边框
    ui->pushButtonCheckout->setFlat(true);
    ui->pushButtonClear->setFlat(true);
    ui->pushButtonClearMember->setFlat(true);
    ui->pushButtonDelete->setFlat(true);
    ui->pushButtonGetOrder->setFlat(true);
    ui->pushButtonInquireCommodity->setFlat(true);
    ui->pushButtonInquireMember->setFlat(true);
    ui->pushButtonLockScreen->setFlat(true);
    ui->pushButtonModify->setFlat(true);
    ui->pushButtonPendingOrder->setFlat(true);
    ui->pushButtonReturnedPurchase->setFlat(true);
    //    ui->labelTotal->setFlat(true);
}

void CommoditySale::on_pushButtonLockScreen_clicked()
{
    m_lockScreen->setWindowFlags(
                Qt::Dialog );
    //在对 QWidget 操作时，不能操作其他东西
    m_lockScreen->setWindowModality(Qt::ApplicationModal);
    m_lockScreen->setAttribute(Qt::WA_ShowModal, true);
    m_lockScreen->move((QApplication::desktop()->width() - m_lockScreen->width())/2,
               (QApplication::desktop()->height() - m_lockScreen->height())/2);
    m_lockScreen->show();
}

void CommoditySale::on_pushButtonInquireCommodity_clicked()
{
    m_inquirePurchaseCommodity->changelineEditInquire(
                ui->lineEditInquireCommodity->text());
    m_inquirePurchaseCommodity->setWindowFlags(
                Qt::FramelessWindowHint | Qt::Dialog);
    QPoint GlobalPoint(ui->pushButtonInquireCommodity
                       ->mapToGlobal(QPoint(0, 0)));
    int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
    int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
    m_inquirePurchaseCommodity->setGeometry(x - 250, y - 440, 800, 425);
    m_inquirePurchaseCommodity->show();

//    m_inquirePurchaseCommodity->setWindowFlags(Qt::Dialog);
//    m_inquirePurchaseCommodity->move((QApplication::desktop()->width()
//                              - m_inquirePurchaseCommodity->width())/2,
//               (QApplication::desktop()->height() - m_inquirePurchaseCommodity->height())/2);
//    m_inquirePurchaseCommodity->setWindowModality(Qt::ApplicationModal);//在对 QWidget 操作时，不能操作其他东西
//    m_inquirePurchaseCommodity->setAttribute(Qt::WA_ShowModal, true);
//    m_inquirePurchaseCommodity->show();

//    QApplication::beep(); //让应用程序发出哔的一声 linux不支持

    //取消底层窗口的置顶
//    parentWidget()->parentWidget()->parentWidget()->hide();
//    parentWidget()->parentWidget()->parentWidget()->setWindowFlags(Qt::Widget);
//    parentWidget()->parentWidget()->parentWidget()->show();
}

void CommoditySale::slotDisplayCommodityInformation(QString commodityBarcode)
{
    addSalesCommodity(commodityBarcode);
    displaySalesCommodityInformation();
    ui->lineEditInquireCommodity->setFocus();
    ui->lineEditInquireCommodity->setText(NULL);
}

void CommoditySale::on_pushButtonCheckout_clicked()
{
    if (ui->tableWidgetSale->rowCount())       
    {
//        m_checkout->setWindowFlags(
//                    Qt::WindowStaysOnTopHint | Qt::Tool );
        m_checkout->setWindowFlags(
                    Qt::Dialog );
        m_checkout->move((QApplication::desktop()->width() - m_checkout->width())/2,
                         (QApplication::desktop()->height() - m_checkout->height())/2);
        //在对 QWidget 操作时，不能操作其他东西
        m_checkout->setWindowModality(Qt::ApplicationModal);
        m_checkout->setAttribute(Qt::WA_ShowModal, true);

        PersonMember personMember;
        if (!ui->lineEditMembershipNumber->text().isEmpty())
            personMember = m_sql->InquireMemberInformation(
                    ui->lineEditMembershipNumber->text());
        else
        {
            personMember.set_personID(tr("非会员"));
            personMember.set_personName(tr("非会员"));
            personMember.set_membercardAmount("0.00");
            personMember.set_integration("0");
        }

        m_checkout->displayMemberInformation(personMember);
        m_checkout->set_amountsReceivable(ui->labelTotal->text());
        m_checkout->set_salesOrderFormNumber(ui->labelSalesOrderFormNumber->text());
        m_checkout->set_quantity(ui->labelQuantity->text());
        m_checkout->set_staffID(MainWindow::staffID);

        //会员消费判断是否积分
        if (!ui->labelName->text().isEmpty())
        {
            //是会员消费 累计积分
            double integrationPrice = 0;
            for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
            {
                QWidget * widget = ui->tableWidgetSale->cellWidget(i, 8); //获得widget
                QCheckBox *checkBox = (QCheckBox*)widget; //强制转化为QComboBox
                checkBox->setEnabled(true);
                if(checkBox->checkState() == Qt::Checked) //选中
                {
                    SaleDetail saleDetail = m_currentTableWidgetList.at(i);
                    saleDetail.set_integration(true);
        //            qDebug() << "false";
                    integrationPrice += saleDetail.get_realSellingPrice().toDouble();
                    m_currentTableWidgetList.replace(i, saleDetail);
                }
                else
                {
                    SaleDetail saleDetail = m_currentTableWidgetList.at(i);
                    saleDetail.set_integration(false);
        //            qDebug() << "true";
                    m_currentTableWidgetList.replace(i, saleDetail);
                }
            }
            if (m_systemSet.get_integrationMode() == 0)
                m_checkout->set_integration("0");
            else
            {
                m_checkout->set_integration(QString::number(
                        (int)integrationPrice/m_systemSet
                                    .get_integrationMode(), 'd', 0));
            }
        }
        else
        {
            //非会员消费 不累计积分
            m_checkout->set_integration("0");
        }

        double costTotal = 0;
        for(int i = 0; i < m_currentTableWidgetList.count(); ++i)
        {
//            qDebug() << m_currentTableWidgetList.at(i).get_cost();
            costTotal += m_currentTableWidgetList.at(i).get_cost().toDouble()
                    * m_currentTableWidgetList.at(i).get_saleQuantity().toInt();
        }

        m_checkout->set_cost(QString::number(costTotal, 'd', 2));
        m_checkout->set_salesDetailsList(m_currentTableWidgetList);
        m_checkout->show();
    }
}

void CommoditySale::on_tableWidgetSale_cellDoubleClicked(int row, int)
{
    if (m_systemSet.get_forbidModifyPricesDiscounts())
    {
        m_modifyPriceDiscount->set_forbidModifyPriceDiscount(true);
        m_modifyPriceDiscount->setMode();
    }
    else
    {
        m_modifyPriceDiscount->set_forbidModifyPriceDiscount(false);
        m_modifyPriceDiscount->setMode();
    }

//    m_modifyPriceDiscount->setWindowFlags(
//                Qt::WindowStaysOnTopHint | Qt::Tool );
    m_modifyPriceDiscount->setWindowFlags( Qt::Dialog );
    m_modifyPriceDiscount->move(
        (QApplication::desktop()->width()  - m_modifyPriceDiscount->width())/2,
        (QApplication::desktop()->height() - m_modifyPriceDiscount->height())/2);
    //在对 QWidget 操作时，不能操作其他东西
    m_modifyPriceDiscount->setWindowModality(Qt::ApplicationModal);
    m_modifyPriceDiscount->setAttribute(Qt::WA_ShowModal, true);
//    m_modifyPriceDiscount->set_staffName();
    SaleDetail temp = m_currentTableWidgetList.at(row);
    temp.set_sellingPrice(ui->tableWidgetSale->item(row, 3)->text());
    temp.set_discount(ui->tableWidgetSale->item(row, 4)->text().replace("%", ""));
    temp.set_realSellingPrice(ui->tableWidgetSale->item(row, 6)->text());
    temp.set_saleSum(ui->tableWidgetSale->item(row, 7)->text());
    m_modifyPriceDiscount->displaySaleCommodityInformation(
                temp);
    m_modifyPriceDiscount->show();
}

void CommoditySale::on_pushButtonInquireMember_clicked()
{
    m_inquireMemberProfile->changelineEditInquire(ui->lineEditMembershipNumber->text());
    m_inquireMemberProfile->setWindowFlags(
                Qt::FramelessWindowHint | Qt::Dialog );
    QPoint GlobalPoint(ui->pushButtonInquireMember->mapToGlobal(QPoint(0, 0)));
    int x = GlobalPoint.x();//该控件在窗体中左上角横坐标
    int y = GlobalPoint.y();//该控件在窗体中左上角纵坐标
    m_inquireMemberProfile->setGeometry(x - 100, y + 30, 800, 415);
    m_inquireMemberProfile->show();
}

void CommoditySale::slotJudgementMemberPassword(QString memberCardNumber)
{
    //检查会员密码
    if (m_systemSet.get_useMemberPassword())
    {
        m_printMemberPassword->move((QApplication::desktop()->width()
                                     - m_printMemberPassword->width())/2,
                         (QApplication::desktop()->height()
                          - m_printMemberPassword->height())/2 - 60);
        m_printMemberPassword->setWindowFlags( Qt::WindowStaysOnTopHint | Qt::Tool );
        //在对 QWidget 操作时，不能操作其他东西
        m_printMemberPassword->setWindowModality(Qt::ApplicationModal);
        m_printMemberPassword->setAttribute(Qt::WA_ShowModal, true);
        PersonMember personMember = m_sql->InquireMemberInformation(memberCardNumber);
        m_printMemberPassword->set_memberPassword(personMember.get_membercardPassword());
        m_printMemberPassword->set_memberCardNumber(memberCardNumber);
        m_printMemberPassword->show();
    }
    else
        slotDisplayMemberInformation(memberCardNumber);
}

void CommoditySale::slotDisplayMemberInformation(QString memberCardNumber)
{
    //显示会员信息
    PersonMember personMember = m_sql->InquireMemberInformation(memberCardNumber);

    ui->lineEditMembershipNumber->setText(personMember.get_personID());
    ui->labelName->setText(personMember.get_personName());
    ui->labelDiscount->setText(personMember.get_discount() + "%");
    m_memberDiscount = personMember.get_discount();
    ui->labelIntegration->setText(personMember.get_integration());
    ui->labelOver->setText(personMember.get_membercardAmount());

    ui->lineEditInquireCommodity->setFocus();
    ui->lineEditInquireCommodity->selectAll();

    displaySalesCommodityInformation();
}

void CommoditySale::on_pushButtonClear_clicked()
{
    if (ui->tableWidgetSale->rowCount() <= 0 && ui->labelName->text().isEmpty())
    {
        ui->lineEditInquireCommodity->setFocus();
        ui->lineEditInquireCommodity->setText(NULL);
        return;
    }
    switch(QMessageBox::question(this, tr("     ★温馨提示★"),
                                 tr("\n您确定要清空所有数据吗?"),
                                 QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes))
    {
        case QMessageBox::Yes:
            ui->tableWidgetSale->clear();
            ui->tableWidgetSale->setRowCount(0);
            m_currentTableWidgetList.clear();
            ui->labelOriginal->setText("0.00");
            ui->labelQuantity->setText("0");
            ui->labelTotal->setText("0.00");
            setQtableWidgetHeader();
            break;
        case QMessageBox::No:
            break;
        default:
            break;
    }
}

void CommoditySale::slotUpdateSalesPriceDiscount(const SaleDetail& saleDetail)
{
    SaleDetail saleCommodity =
            m_currentTableWidgetList.at(ui->tableWidgetSale->currentRow());

    saleCommodity.set_saleQuantity(saleDetail.get_saleQuantity());
    saleCommodity.set_discount(saleDetail.get_discount());
    saleCommodity.set_realSellingPrice(saleDetail.get_realSellingPrice());
    saleCommodity.set_saleSum(saleDetail.get_saleSum());
    m_currentTableWidgetList.replace(ui->tableWidgetSale->currentRow(), saleCommodity);
    m_updateSaleCommodityInformation = true;

    displaySalesCommodityInformation();
}

//void CommoditySale::on_tableWidgetSale_cellClicked(int row, int column)
//{
//    //会员消费判断是否积分
//    if (column == 8 && (!ui->labelName->text().isEmpty()))
//    {
//        QWidget * widget = ui->tableWidgetSale->cellWidget(row, 8); //获得widget
//        QCheckBox *checkBox = (QCheckBox*)widget; //强制转化为QComboBox
//        checkBox->setEnabled(true);
//        if(checkBox->checkState() == Qt::Checked) //选中
//        {
//            checkBox->setCheckState(Qt::Unchecked);
//            SaleDetail saleDetail = m_currentTableWidgetList.at(row);
//            saleDetail.set_integration(false);
////            qDebug() << "false";
//            m_currentTableWidgetList.replace(row, saleDetail);
//        }
//        else
//        {
//            checkBox->setCheckState(Qt::Checked);
//            SaleDetail saleDetail = m_currentTableWidgetList.at(row);
//            saleDetail.set_integration(true);
////            qDebug() << "true";
//            m_currentTableWidgetList.replace(row, saleDetail);
//        }
//    }
//}

void CommoditySale::on_pushButtonClearMember_clicked()
{
    ui->lineEditMembershipNumber->setText(NULL);
    ui->labelName->setText(NULL);
    ui->labelDiscount->setText(NULL);
    ui->labelIntegration->setText(NULL);
    ui->labelOver->setText(NULL);

    ui->lineEditInquireCommodity->setFocus();
    ui->lineEditInquireCommodity->selectAll();
    displaySalesCommodityInformation();
}

void CommoditySale::on_pushButtonDelete_clicked()
{
    if (ui->tableWidgetSale->rowCount())
    {
        m_currentTableWidgetList.removeAt(ui->tableWidgetSale->currentRow());
        displaySalesCommodityInformation();
    }
}

void CommoditySale::slotInit()
{
    ui->tableWidgetSale->clear();
    ui->tableWidgetSale->setRowCount(0);
    m_currentTableWidgetList.clear();
    ui->labelOriginal->setText("0.00");
    ui->labelQuantity->setText("0");
    ui->labelTotal->setText("0.00");
    setQtableWidgetHeader();

    on_pushButtonClearMember_clicked();

    setSalesOrderFormNumber();
}

//void CommoditySale::slotCheckOut()
//{
////    QString a = "8.69";
////    qDebug() << QString::number((int)a.toDouble()/10, 'd', 0);

//    SaleOrderForm saleOrderForm(ui->labelSalesOrderFormNumber->text(),
//                                ui->lineEditMembershipNumber->text(),
//                                ui->labelName->text(),
//                                ui->labelQuantity->text(),
//                                ui->labelTotal->text(),
//                                QString::number((int)ui->labelTotal->text().toDouble()/10, 'd', 0),
//                                );

//    if (!m_sql->InsertSalesOrderForm(saleOrderForm))
//    {
//        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("插入销售单据失败") );
//        return;
//    }
//    if (!m_sql->InsertSalesDetail(m_currentTableWidgetList))
//    {
//        QMessageBox::information(this, tr("(☆_☆)温馨提示 ..."), tr("插入进货明细失败") );
//        return;
//    }
//    m_purchaseReceipt->displayTableWidgetPurchaseOrderForm();
//    returnInitStatus();
//    initStatus = true;
//}

//void CommoditySale::on_lineEditInquireCommodity_textChanged(const QString &arg1)
//{

//}
